package com.example.wechat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

//处理消息的handler
public class WebServerHander extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private static ChannelGroup clients=new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println("接受到了消息"+text);
//        for (Channel channel :clients) {
//            channel.writeAndFlush(
//                    new TextWebSocketFrame("服务器接收到消息"+ LocalDateTime.now()+"接受到消息为"+text)
//            );
//        }
        clients.writeAndFlush(new TextWebSocketFrame(
                "服务器接收到消息"+ LocalDateTime.now()+"接受到消息为"+text
        ));

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        clients.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        clients.remove(ctx.channel());
        System.out.println("长id为"+ctx.channel().id().asLongText());
        System.out.println("短id为"+ctx.channel().id().asLongText());
        //super.handlerRemoved(ctx);
    }
}
